Skip to content

EntityRegexSearch module

EntityRegexSearch

Bases: Retriever

Regex matching over entities of a single label.

Graph-side counterpart of RegexSearch. Thin deterministic wrapper around KnowledgeBase.entity_regex_search. Regex uses RE2 (DuckDB's engine), so patterns are linear-time and not vulnerable to catastrophic backtracking.

Single-label only: to retrieve entities of multiple labels, compose several EntityRegexSearch modules in the program DAG and merge their outputs explicitly.

Parameters:

Name Type Description Default
knowledge_base KnowledgeBase

The knowledge base to search. Required.

required
schema dict

JSON schema of the entity. Used to infer label from its title when not given explicitly. Mutually inferrable with entity_model.

None
entity_model Entity | SymbolicDataModel

Entity model providing schema via .get_schema() when schema is not given.

None
label str

Target entity label. Defaults to the schema's title. Optional: when neither label nor a schema to derive it from is given, the language model infers the target entity label per call (constrained to the knowledge base's actual entity labels).

None
k int

Maximum number of results. Defaults to 10.

required
fields list

Field names to match against. Defaults to every string field on the schema.

None
case_sensitive bool

When False, regex matches are case-insensitive. Defaults to True.

True
output_format str

"json" (default) or "csv".

required
name str

Module name.

required
description str

Module description.

required
trainable bool

Whether the module's variables should be trainable.

required
Source code in synalinks/src/modules/retrievers/entity_regex_search.py
@synalinks_export(
    [
        "synalinks.modules.EntityRegexSearch",
        "synalinks.EntityRegexSearch",
    ]
)
class EntityRegexSearch(Retriever):
    """Regex matching over entities of a single label.

    Graph-side counterpart of `RegexSearch`. Thin
    deterministic wrapper around
    `KnowledgeBase.entity_regex_search`. Regex uses RE2
    (DuckDB's engine), so patterns are linear-time and not vulnerable
    to catastrophic backtracking.

    Single-label only: to retrieve entities of multiple labels,
    compose several `EntityRegexSearch` modules in the program
    DAG and merge their outputs explicitly.

    Args:
        knowledge_base (KnowledgeBase): The knowledge base to search.
            Required.
        schema (dict): JSON schema of the entity. Used to infer
            ``label`` from its ``title`` when not given explicitly.
            Mutually inferrable with ``entity_model``.
        entity_model (Entity | SymbolicDataModel): Entity model
            providing ``schema`` via ``.get_schema()`` when ``schema``
            is not given.
        label (str): Target entity label. Defaults to the schema's
            ``title``. **Optional**: when neither ``label`` nor a
            schema to derive it from is given, the language model infers
            the target entity label per call (constrained to the
            knowledge base's actual entity labels).
        k (int): Maximum number of results. Defaults to 10.
        fields (list): Field names to match against. Defaults to
            every string field on the schema.
        case_sensitive (bool): When ``False``, regex matches are
            case-insensitive. Defaults to ``True``.
        output_format (str): ``"json"`` (default) or ``"csv"``.
        name (str): Module name.
        description (str): Module description.
        trainable (bool): Whether the module's variables should be
            trainable.
    """

    query_model = EntityRegexSearchInput
    data_model_args = ("entity_model",)

    def __init__(
        self,
        *,
        schema=None,
        entity_model=None,
        label: Optional[str] = None,
        fields: Optional[List[str]] = None,
        case_sensitive: bool = True,
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.schema, self.label = resolve_target(schema, entity_model, label)
        self.entity_model = entity_model
        self.fields = fields
        self.case_sensitive = case_sensitive

        self.build_query_generator(
            [
                (
                    "entity_label",
                    "The entity label to search, chosen to best answer the inputs.",
                    kb_entity_labels(self.knowledge_base),
                )
            ]
            if self.label is None
            else []
        )

    async def search(self, query):
        query_json = query.get_json()
        pattern = query_json.get("regex_search")
        # Fixed label, or the one the LM inferred this call.
        label = self.label or query_json.get("entity_label")
        if not pattern or not label:
            return None

        rows = await self.knowledge_base.entity_regex_search(
            pattern,
            label=label,
            fields=self.fields,
            case_sensitive=self.case_sensitive,
            k=self.k,
            output_format=self.output_format,
        )
        return {"result": rows}

    def get_config(self):
        return {
            "schema": self.schema,
            "label": self.label,
            "k": self.k,
            "fields": list(self.fields) if self.fields is not None else None,
            "case_sensitive": self.case_sensitive,
            "output_format": self.output_format,
            **super().get_config(),
        }

EntityRegexSearchInput

Bases: DataModel

Input shape for EntityRegexSearch.

Source code in synalinks/src/modules/retrievers/entity_regex_search.py
class EntityRegexSearchInput(DataModel):
    """Input shape for `EntityRegexSearch`."""

    regex_search: str = Field(
        description=(
            "Regex pattern (RE2 syntax) to match against the entity's string fields"
        ),
    )